package ltd.dujiabao.capability.application.capmng;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ltd.dujiabao.capability.domain.capmng.cap.Capability;
import ltd.dujiabao.capability.domain.capmng.cap.CapabilityIdentity;
import ltd.dujiabao.capability.domain.capmng.cap.CapabilityRepository;
import ltd.dujiabao.capability.domain.capmng.sync.Synchronizer;
import ltd.dujiabao.capability.domain.capmng.sync.SynchronizerBuilder;
import ltd.dujiabao.capability.domain.capmng.sync.SynchronizerBuilderFactory;
import ltd.dujiabao.capability.domain.devmng.DevInfo;
import ltd.dujiabao.capability.domain.devmng.DevInfoRepository;

/**
 * @author : DuJiabao
 * @Project : ddd-capability
 * @Time : 2024/4/6 21:18
 * @Desc :
 */
@Service
public class CapabilityServiceImpl implements CapabilityService {

    private final CapabilityRepository capabilityRepository;

    private final SynchronizerBuilderFactory synchronizerBuilderFactory;

    private final DevInfoRepository devInfoRepository;

    @Autowired
    public CapabilityServiceImpl(CapabilityRepository capabilityRepository,
                                 SynchronizerBuilderFactory synchronizerBuilderFactory,
                                 DevInfoRepository devInfoRepository) {
        this.capabilityRepository = capabilityRepository;
        this.synchronizerBuilderFactory = synchronizerBuilderFactory;
        this.devInfoRepository = devInfoRepository;
    }

    @Override
    public void syncCapability(SyncCapabilityDTO dto) {
        // 查询设备版本
        DevInfo devInfo = devInfoRepository.findByDevId(dto.getDevId());

        // 检查是否存在，若已存在，直接返回
        CapabilityIdentity capabilityIdentity
                = new CapabilityIdentity(devInfo.getDevModelId(), devInfo.getHardwareVer(), devInfo.getFirmwareVer());
        if (capabilityRepository.exists(capabilityIdentity)) {
            return;
        }

        // 查询同步器
        SynchronizerBuilder synchronizerBuilder = synchronizerBuilderFactory.createBuilder(devInfo.getDevType());
        Synchronizer synchronizer = synchronizerBuilder
                .setAttributes(dto.getExtendInfo())
                .build();

        // 同步capability
        Capability capability = synchronizer.syncCapability(devInfo);

        // 保存Capability
        capabilityRepository.save(capability);
    }
}
